package com.freeheart.validation.constraintvalidators.recent;


import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author: EmperorHeart
 * @date: 2025/5/10 1:20
 * @description
 */
public class CompositionRecentConstraintValidator extends AbstractRecentConstraintValidator {

    private List<ComputeGap> computeGapList;

    public CompositionRecentConstraintValidator() {
        super();
        this.computeGapList = loadComputeGapList();
    }

    private List<ComputeGap> loadComputeGapList() {
        ServiceLoader<ComputeGap> load = ServiceLoader.load(ComputeGap.class);
        List<ComputeGap> gaps = new ArrayList<>();
        load.forEach(gaps::add);
        AnnotationAwareOrderComparator.sort(gaps);
        return gaps;
    }


    @Override
    protected long computeGap(Object object, RecentProperties rp) {
        for (ComputeGap computeGap : computeGapList) {
            if (computeGap.support(object)) {
                return computeGap.compute(object, rp);
            }
        }
        throw new NoSupportTypeRecentException("不支持对" + object.getClass() + "类型进行@Recent注解计算解析");
    }
}
